package com.xuef.ibatis.binding;

import com.xuef.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by xuefengDong: moveb
 * On 2019/4/25- 21:07
 */
public class MapperProxy<T> implements InvocationHandler {
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    //接口中方法的缓存 由 MapperProxyFactory传递过来的。
    private final Map<Method, MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface,
                       Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    //接口代理对象所有的方法调用 都会调用该方法
    //这儿的 method 与接口中的方法对应，将在调用时由系统生成
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //判断是不是基础方法 比如toString() hashCode()等，这些方法直接调用不需要处理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        //这里进行缓存
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        //调用 mapperMethod.execute 核心的地方就在这个方法里，这个方法才是真正对SqlSession进行的包装调用
        return mapperMethod.execute(sqlSession, args);
    }
    //缓存处理
    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }

}
